﻿//<TunynetCopyright>
//--------------------------------------------------------------
//<copyright>青岛拓宇网络科技有限公司 2005-2008</copyright>
//<version>V0.5</verion>
//<createdate>2008-2-22</createdate>
//<author>zhengw</author>
//<email>zhengw@tunynet.com</email>
//<log date="2008-2-22">创建</log>
//--------------------------------------------------------------
//</TunynetCopyright>

using System;
using System.Collections.Generic;
using System.Text;
using Tunynet.QingdaoCustoms.Common;
using ChinaCustoms.Framework.DeluxeWorks.Library.OGUPermission;
using ChinaCustoms.Qingdao.Workflow.Permissions;

namespace ChinaCustoms.Qingdao.Workflow.Supports
{
    /// <summary>
    /// 活动实例业务逻辑类
    /// </summary>
    public class ActivityInstances
    {
        /// <summary>
        /// 创建普通活动实例
        /// </summary>
        /// <param name="activityInstanceInfo">活动实例</param>
        /// <param name="creatorUserName">创建人UserName</param>
        /// <param name="initializeWorkItems">是否自动初始化工作项</param>
        public static CreateActivityResult CreateActivity(ActivityInstanceInfo activityInstanceInfo, bool isInitializeWorkItems, string creatorUserName, Guid previousWorkItemGuid, SubTaskInfo subTask)
        {
            int createdWorkItemCount = 0;

            //子流程的活动
            if (activityInstanceInfo.SubFlowGuid != Guid.Empty && subTask != null)
            {
                if (isInitializeWorkItems)
                {
                    createdWorkItemCount = WorkItems.InitializeWorkItems(activityInstanceInfo, creatorUserName, previousWorkItemGuid, subTask);
                    if (createdWorkItemCount == 0)
                        return CreateActivityResult.NoExecutors;
                }
            }
            else
            {
                if (isInitializeWorkItems)
                {
                    createdWorkItemCount = WorkItems.InitializeWorkItems(activityInstanceInfo, creatorUserName, previousWorkItemGuid, null);
                    if (createdWorkItemCount == 0)
                        return CreateActivityResult.NoExecutors;
                }
            }

            if (subTask != null)
                activityInstanceInfo.SubTaskGuid = subTask.SubTaskGuid;

            WorkflowTrackingDataProvider.Instance().CreateUpdateActivity(activityInstanceInfo, DataProviderAction.Create);

            return CreateActivityResult.Success;

            ////更新ExecutingActivityCodeName
            //WorkflowInstanceInfo workflowInstanceInfo = WorkflowInstances.GetWorkflow(activityInstanceInfo.WorkflowGuid);
            //if (workflowInstanceInfo != null)
            //{
            //    workflowInstanceInfo.ExecutingActivityCodeName = activityInstanceInfo.CodeName;
            //    WorkflowInstances.UpdateWorkflow(workflowInstanceInfo);
            //}
        }

        /// <summary>
        /// 创建子流程活动
        /// </summary>
        /// <param name="activityInstanceInfo"></param>
        /// <param name="organizationIDs"></param>
        /// <param name="creatorUserName"></param>
        /// <param name="previousWorkItemGuid"></param>
        public static CreateActivityResult CreateSubFlowActivity(ActivityInstanceInfo activityInstanceInfo, string[] organizationIDs, string creatorUserName, Guid previousWorkItemGuid)
        {
            SubFlowInfo subFlow = SubFlows.GetSubFlowByActivityPrototypeGuid(activityInstanceInfo.PrototypeGuid);
            TaskInfo taskInfo = Tasks.GetTaskByWorkflowGuid(activityInstanceInfo.WorkflowGuid);
            IUser creator = ChinaCustomsPermissionWrapper.GetUser(creatorUserName);

            if (subFlow != null)
            {
                foreach (string organizationID in organizationIDs)
                {
                    IOrganization organization = ChinaCustomsPermissionWrapper.GetOrganization(organizationID);
                    if (organization != null)
                    {
                        SubTaskInfo newSubTask = new SubTaskInfo();
                        newSubTask.SubTaskGuid = Guid.NewGuid();
                        newSubTask.ParentSubTaskGuid = activityInstanceInfo.SubTaskGuid;
                        newSubTask.SubTaskName = activityInstanceInfo.ActivityName;
                        newSubTask.ActivityGuid = activityInstanceInfo.ActivityGuid;
                        newSubTask.TaskGuid = taskInfo.TaskGuid;
                        newSubTask.SubFlowGuid = subFlow.SubFlowGuid;
                        newSubTask.OrganizationID = new Guid(organization.ID);
                        newSubTask.OrganizationName = organization.Name;
                        newSubTask.SponsorUserName = creator.LogOnName;
                        newSubTask.SponsorDisplayName = creator.DisplayName;
                        newSubTask.SponsorFullPath = creator.FullPath;

                        SubTasks.CreateSubTask(newSubTask);

                        ActivityPrototypeInfo firstActivityPrototypeOfSubTask = ActivityPrototypes.GetFirstActivityPrototypeOfSubFlow(subFlow.WorkflowGuid, subFlow.SubFlowGuid);
                        ActivityInstanceInfo firstActivityOfSubTask = new ActivityInstanceInfo(firstActivityPrototypeOfSubTask);

                        CreateActivity(firstActivityOfSubTask, true, creatorUserName, previousWorkItemGuid, newSubTask);
                    }
                }
            }

            WorkflowTrackingDataProvider.Instance().CreateUpdateActivity(activityInstanceInfo, DataProviderAction.Create);
            //如果该子流程活动不需反馈则直接向下流转
            if (!activityInstanceInfo.RequireFeedbackInSubFlow)
            {
                if (!activityInstanceInfo.StartSubFlowAndStopThisFlow)
                {
                    WorkItemInfo workItemInfo = new WorkItemInfo();
                    workItemInfo.WorkItemGuid = Guid.NewGuid();

                    workItemInfo.ActivityGuid = activityInstanceInfo.ActivityGuid;
                    workItemInfo.ActivityName = activityInstanceInfo.ActivityName;
                    workItemInfo.TaskGuid = taskInfo.TaskGuid;
                    workItemInfo.SubTaskGuid = activityInstanceInfo.SubTaskGuid;
                    workItemInfo.WorkItemType = WorkItemType.ApprovalAndNavigation;
                    workItemInfo.Status = WorkItemStatus.Executing;

                    workItemInfo.CreatorUserName = creator.LogOnName;
                    workItemInfo.CreatorDisplayName = creator.DisplayName;
                    workItemInfo.CreatorFullPath = creator.FullPath;

                    workItemInfo.ExecutorUserName = creator.LogOnName;
                    workItemInfo.ExecutorDisplayName = creator.DisplayName;
                    workItemInfo.ExecutorFullPath = creator.FullPath;

                    workItemInfo.WorkItemName = string.Format("{0}-审批-{1}", activityInstanceInfo.ActivityName, creator.LogOnName);
                    workItemInfo.PreviousWorkItemGuid = previousWorkItemGuid;
                    BusinessDataProvider.Instance().CreateUpdateWorkItem(workItemInfo, DataProviderAction.Create);
                }                
            }

            return CreateActivityResult.Success;
        }


        /// <summary>
        /// 更新活动实例
        /// </summary>
        public static void UpdateActivity(ActivityInstanceInfo activityInstanceInfo)
        {
            WorkflowTrackingDataProvider.Instance().CreateUpdateActivity(activityInstanceInfo, DataProviderAction.Update);
        }

        /// <summary>
        /// 获取活动实例
        /// </summary>
        public static ActivityInstanceInfo GetActivity(Guid activityGuid)
        {
            return WorkflowTrackingDataProvider.Instance().GetActivity(activityGuid);
        }

        /// <summary>
        /// 获取同一工作流实例中具备相同CodeName的最新活动实例
        /// </summary>
        public static ActivityInstanceInfo GetLastActivityByCodeName(Guid workflowGuid, Guid subTaskGuid, string activityCodeName)
        {
            return WorkflowTrackingDataProvider.Instance().GetLastActivityByCodeName(workflowGuid, subTaskGuid, activityCodeName);
        }

        /// <summary>
        /// 获取工作流实例的所有活动
        /// </summary>
        public static List<ActivityInstanceInfo> GetActivities(Guid workflowGuid, Guid? subTaskGuid)
        {
            return WorkflowTrackingDataProvider.Instance().GetActivities(workflowGuid, subTaskGuid);
        }

        /// <summary>
        /// 更新活动实例状态
        /// </summary>
        public static void ChangeActivityStatus(Guid activityGuid, ActivityStatus activityStatus)
        {
            WorkflowTrackingDataProvider.Instance().ChangeActivityStatus(activityGuid, activityStatus);
        }


        /// <summary>
        /// 回退到某个活动
        /// </summary>
        /// <remarks>
        /// 创建新的活动实例，并且把该活动以前的工作项重新执行
        /// </remarks>
        /// <param name="activityGuid">回退到的活动Guid</param>
        public static void BackActivity(Guid activityGuid, Guid previousWorkItemGuid, IUser creator)
        {
            ActivityInstanceInfo redoActivity = ActivityInstances.GetActivity(activityGuid);
            if (redoActivity != null)
            {
                if (redoActivity.IsSubFlow)
                {
                    ActivityPrototypeInfo activityPrototype = ActivityPrototypes.GetActivityPrototype(redoActivity.PrototypeGuid);
                    ActivityInstanceInfo newActivity = new ActivityInstanceInfo(redoActivity);
                    //newActivity.SubTaskGuid = subTaskGuid;
                    CreateSubFlowActivity(newActivity, newActivity.RequiredDepartmentIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), creator.LogOnName, previousWorkItemGuid);
                }
                else
                {
                    ActivityInstanceInfo newActivity = new ActivityInstanceInfo(redoActivity);
                    //newActivity.SubTaskGuid = subTaskGuid;
                    ActivityInstances.CreateActivity(newActivity, false, null, Guid.Empty, null);

                    //生成新的redoActivity活动执行成功的工作项
                    WorkItemInfo newWorkItem = WorkItems.GetOneWorkItemOfActivity(redoActivity.ActivityGuid, WorkItemStatus.Completed);
                    newWorkItem.WorkItemGuid = Guid.NewGuid();
                    newWorkItem.Postil = string.Empty;
                    newWorkItem.Status = WorkItemStatus.Executing;
                    newWorkItem.ActivityGuid = newActivity.ActivityGuid;
                    newWorkItem.PreviousWorkItemGuid = previousWorkItemGuid;
                    newWorkItem.CreatorUserName = creator.LogOnName;
                    newWorkItem.CreatorDisplayName = creator.DisplayName;
                    newWorkItem.CreatorFullPath = creator.FullPath;
                    WorkItems.CreateWorkItem(newWorkItem);
                }

                //只更新主流程的活动
                //更新TaskInfo中当前运行的ActivityCodeName
                if (redoActivity.SubFlowGuid == Guid.Empty)
                {
                    TaskInfo task = Tasks.GetTaskByWorkflowGuid(redoActivity.WorkflowGuid);
                    task.ExecutingActivityCodeName = redoActivity.CodeName;
                    Tasks.UpdateTask(task);
                }
            }
        }


    }
}
